﻿using System;
using System.Collections.Generic;
using System.Reflection;
using K9Nano.Extensions;
using Mapster;
using MapsterMapper;

namespace K9Nano.Mapping;

public static class MappingHelper
{
    private static readonly Dictionary<Assembly, TypeAdapterConfig> Configs = new();

    public static IMapper Mapper
    {
        get
        {
            var assembly = Assembly.GetCallingAssembly();
            if (!Configs.TryGetValue(assembly, out var config))
            {
                var setupType = ReflectionHelper.GetImplementType<IMappingSetup>(assembly, false, false);
                if (setupType != null)
                {
                    if (Activator.CreateInstance(setupType) is IMappingSetup setup)
                    {
                        config = TypeAdapterConfig.GlobalSettings.Clone();
                        setup.Setup(config);
                    }
                }

                Configs[assembly] = config ??= TypeAdapterConfig.GlobalSettings;
            }
            return new Mapper(config);
        }
    }
}